from PyQt4 import QtGui
import sys

import qt4reactor
qt4reactor.install()

import displayWidget
import readers
import musicPlayer
import stdActions
import preferenceManager
import servers
import networkActions

from twisted.internet import reactor

class Eleanor(QtGui.QMainWindow):
    """Eleanor itself"""
    def __init__(self, profiles, preferences):
        QtGui.QMainWindow.__init__(self)
        self.resize(1000,600)
        self.setWindowTitle('Eleanor')
        self.show()
        preferenceManager.manage(preferences, self)
        self.profiles=profiles
        centralWidget=displayWidget.TabDisplay(self)
        self.setCentralWidget(centralWidget)
        menuBar=self.menuBar()
        toolBar=self.addToolBar('Networking')
        for name, profile in self.profiles.iteritems():
            trayDisplay=displayWidget.TrayDisplay(profile, centralWidget)
            trayDisplay.tableWidget.setAcceptor(name)
            centralWidget.addWidget(name, trayDisplay)
            if name=='Songs':
                playing=musicPlayer.NowPlaying(profile.atts)
                centralWidget.addWidget('Now Playing', playing.table)
                self.addToolBar(playing.getToolbar())
                trayDisplay.tableWidget.listener=playing
                stdActions.addMenu(menuBar, self, self.profiles,
                                   trayDisplay.tableWidget, centralWidget)
                networkActions.addIntoTool(toolBar, centralWidget, profiles,
                                           trayDisplay.tableWidget, playing)
        centralWidget.addMenu(menuBar, self)
        stdActions.addHelp(menuBar, self)
        name=self.profiles.keys()[0]
        centralWidget.activate(name)
    def save(self):
        """Saves all of the profiles"""
        for profile in self.profiles.itervalues():
            profile.save()
        
def main(profileFile='qdata\\profiles.json',
         preferenceFile='qdata\\preferences.json'):
    profiles=readers.loadProfiles(profileFile)
    preferences=readers.loadFromJson(preferenceFile)
    servers.listen(profiles, preferences)
    app=QtGui.QApplication(sys.argv)
    window=Eleanor(profiles, preferences)
    app#Protecting from garbage collection
    #app.exec_()
    reactor.run()
    window.save()

def profileMain():
    from hotshot import Profile, stats
    prof=Profile('proflog2')
    prof.runcall(main)
    prof.close()
    stats.load('proflog2').sort_stats('time').print_stats()

if __name__ == '__main__':
    try:
        #profileMain()
        main(*sys.argv[1:])
    except IndexError:
        main()
